import { defineStore } from "pinia";
import type { PersistenceOptions } from "pinia-plugin-persistedstate";
import { nextTick, reactive } from "vue";
import { userStore } from "./userStore"
import { ElMessage } from "element-plus";
import type { ChatDataWithCurrentuser, ChatList, ChatMessage, FriendRequest, RecommendFriends, UserFriendInfo } from "../types/types";


interface ChatListObject {
    [key: string]: string[]
}

export const friendStore = defineStore('friendStore', () => {

    // 存储聊天列表
    const mergeList = reactive<ChatList[]>([]);           // 这个才是最终使用的变量
    const storageChatList = reactive<ChatListObject>({
        "groupList": [],
        "friendList": []
    });
    // 存储变量
    function storageList(groupList: string[], friendList: string[]) {
        const group_list = Array.isArray(groupList) ? groupList : [groupList];
        const friend_list = Array.isArray(friendList) ? friendList : [friendList];
        // 解析groupList和friendList并扩展一个属性用来区分群聊和私聊，后期还会有临时聊天
        const parsedGroupList = group_list.map(group => {
            const parsedGroup = JSON.parse(group);
            parsedGroup.type = "group-chat";
            return parsedGroup;
        });
        const parsedFriendList = friend_list.map(friend => {
            const parsedFriend = JSON.parse(friend);
            parsedFriend.type = "private-chat";
            return parsedFriend;
        });
        // 存储解析之后的json字符串
        storageChatList['groupList'] = parsedGroupList;
        storageChatList['friendList'] = parsedFriendList;

        // 将两个数组合并到mergeList变量中
        mergeList.splice(0, mergeList.length, ...parsedGroupList, ...parsedFriendList);
    }
    // 单独添加的操作
    function addToMergeList(item: ChatList) {
        // 确保item是包含type属性的（通过这个属性可以区分聊天对象的类型（群聊、私聊、临聊））
        if (!item.type) {
            console.error("The item must have a 'type' property.");
            return;
        }
        // 将对象直接添加到mergeList中
        mergeList.push(item);
        // 根据type属性将item对象添加到storageChatList中（同时将数据更新到storageChatList对应的列表中）
        if (item.type === "group-chat") {
            storageChatList.groupList.push(JSON.stringify(item));
        } else if (item.type === "private-chat") {
            storageChatList.friendList.push(JSON.stringify(item));
        } else {
            console.error("Invalid type. Only 'group-chat' and 'private-chat' are allowed.");
            // 如果类型无效，从mergeList中移除该对象
            const index = mergeList.indexOf(item);
            if (index !== -1) {
                mergeList.splice(index, 1);
            }
            return;
        }
    }

    const recommendFriends = reactive<RecommendFriends[]>([]);

    function storageRecommendFriends(recommend_friends: RecommendFriends) {
        if (recommendFriends.some(friend => friend.uu_id === recommend_friends.uu_id)) {
            return;
        } else {
            recommendFriends.push(recommend_friends);
        }
    }


    // 存储好友请求列表信息
    const storageFriendRequestList = reactive<FriendRequest[]>([]);
    function setFriendRequestList(list: FriendRequest[]) {
        console.log(list)
        const listArray = Array.isArray(list) ? list : [list];
        // 直接将所有的好友请求元素添加到storageFriendRequestList
        storageFriendRequestList.push(...listArray);
        console.log(storageFriendRequestList)
    }
    function removeFriendRequestById(requestId: string) {
        console.log(requestId);
        // 找到要删除的请求的索引
        const index = storageFriendRequestList.findIndex((request: FriendRequest) => {
            return request.requestId === requestId;
        })
        console.log(index);
        if (index !== -1) {
            storageFriendRequestList.splice(index, 1);
        } else {
            ElMessage.warning("请求信息删除失败");
        }
    }

    // 存储聊天记录信息
    const storageFriendChatMessae = reactive<ChatDataWithCurrentuser>({
        chatData: {},
        currentUserId: userStore().userInfo.uu_id
    });
    function storageMessage(friendId: string, chatContent: ChatMessage | ChatMessage[], shouldAppend: boolean = false) {
        if (!storageFriendChatMessae.chatData[friendId]) {
            // 如果 chatData[friendId] 不存在，初始化为一个空数组
            storageFriendChatMessae.chatData[friendId] = [];
        }

        if (!shouldAppend) {
            // 如果 shouldAppend 为 false，直接覆盖数组
            storageFriendChatMessae.chatData[friendId] = Array.isArray(chatContent) ? chatContent : [chatContent];
        } else {
            // 如果 shouldAppend 为 true，追加到数组中
            if (Array.isArray(chatContent)) {
                storageFriendChatMessae.chatData[friendId].push(...chatContent);
            } else {
                storageFriendChatMessae.chatData[friendId].push(chatContent);
            }
        }
    }

    /* ------------------------存储用户好友信息--------------- */
    const storageUserFriendList = reactive<UserFriendInfo[]>([]);
    function setFriendList(data: UserFriendInfo[]) {
        storageUserFriendList.splice(0, storageUserFriendList.length, ...data);
    }
    // 通过uuId在storageUserFriendList中查询对应的信息并返回
    function getFriendListFromUserId(userId: string): UserFriendInfo | undefined {
        return storageUserFriendList.find((friend: UserFriendInfo) => {
            return userId == friend.friendDetails.uu_id;
        })
    }
    // 通过uuId获取label和avatar信息
    function getLabelAndAvatarByUUID(userId: string): { key: string; label: string; avatar: string; } | undefined {
        // 在数据源中查找匹配的用户
        const friend = storageUserFriendList.find((friend: UserFriendInfo) => friend.friendDetails.uu_id === userId);
        if (friend) {
            // 直接获取详细信息，避免多余的对象属性调用
            const friendDetails = friend.friendDetails;
            return {
                key: friendDetails.uu_id,
                label: friendDetails.username,
                avatar: friendDetails.avatar
            }
        } else {
            ElMessage.warning("未找到匹配的好友信息！");
        }
    }
    // 设置用户备注和分组信息
    function setUserRemarkOrGroupInfo(type: string, friendId: string, info: string | null) {
        const friend = getFriendListFromUserId(friendId);
        if (!friend) {
            ElMessage.error("未找到用户！");
            return;
        }
        const actions = {
            'set-remark-info': () => {
                friend.remark = info!;
            },
            'set-group-info': () => {
            }
        }
        const action = actions[type as keyof typeof actions];
        if (action) {
            action();
            if (info !== null) {
            } else {
                ElMessage.warning("信息未提供！");
            }
        } else {
            return;
        }
    }



    return {
        /* 存储聊天列表 */
        mergeList, storageList, addToMergeList,


        /* 存储好友列表 */
        storageUserFriendList,
        setFriendList,
        getFriendListFromUserId,
        setUserRemarkOrGroupInfo,
        getLabelAndAvatarByUUID,

        /*  存储推荐好友信息 */
        recommendFriends, storageRecommendFriends,


        /*  请求信息  */
        storageFriendRequestList, setFriendRequestList, storageFriendChatMessae, storageMessage, removeFriendRequestById
    }

}, {
    persist: {
        key: 'friendStore',
        paths: ['recommendFriends', 'storageFriendRequestList', 'storageFriendChatMessae'],
        storage: localStorage
    } as PersistenceOptions
})